package com.aspire.moss.portal.desktop;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;

import com.aspire.moss.portal.R;

/**
 * 第一页的应用
 * 
 * @author Administrator
 * 
 */
public class CellLayout extends ViewGroup {

	private static final String TAG = "CellLayout";

	private static final int MOVE_ICON_TIME = 250;

	private int mWidth, mHeight;// 控件的宽度,高度

	public int screenId;// 屏幕id

	private float clos, rows; // 当前页能显示的行数和列数

	private int cellWidth, cellHeight;// 每个子控件应该占的高度与宽度,但是控件要排在这个宽度中间的

	private float mCellWidth, mCellHeigth;// 每个了控件的实际高度与宽度

	private static final int DEL_VIEW = 0;

	private static final int DEL_MOVE = 1;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DEL_VIEW:
				removeViewAt(msg.arg1);
				break;
			case DEL_MOVE:
				if (null != msg.obj && msg.obj instanceof Boolean) {
					clearUp(msg.arg1, msg.arg2, true);
				} else {
					clearUp(msg.arg1, msg.arg2, false);
				}
				break;
			}

			super.handleMessage(msg);
		}

	};

	Context mContext;

	public CellLayout(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public CellLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.CellLayout);
		clos = a.getInt(R.styleable.CellLayout_clos, 4);
		rows = a.getInt(R.styleable.CellLayout_rows, 4);
		mCellWidth = a.getDimension(R.styleable.CellLayout_cellWidth, 80);
		mCellHeigth = a.getDimension(R.styleable.CellLayout_cellHeight, 80);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		mWidth = MeasureSpec.getSize(widthMeasureSpec);
		mHeight = MeasureSpec.getSize(heightMeasureSpec);

		final int mpmWidth = (int) (mWidth - getPaddingLeft() - getPaddingRight());
		final int mpmHeight = (int) (mHeight - getPaddingTop() - getPaddingBottom());

		cellWidth = (int) (mpmWidth / clos);
		cellHeight = (int) (mpmHeight / rows);
		View child = null;
		for (int i = 0; i < getChildCount(); i++) {
			child = getChildAt(i);
			final int childWidth = MeasureSpec.makeMeasureSpec(
					(int) mCellWidth, MeasureSpec.EXACTLY);
			final int childHeigth = MeasureSpec.makeMeasureSpec(
					(int) mCellHeigth, MeasureSpec.EXACTLY);
			child.measure(childWidth, childHeigth);
		}
		final int measuredHeight = FrameLayout.resolveSize(heightMeasureSpec,
				heightMeasureSpec);
		setMeasuredDimension(widthMeasureSpec, measuredHeight);
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		Log.d(TAG, "onLayout screenId =" + screenId + " getChildCount="
				+ getChildCount());
		CellView child = null;
		AppInfo info = null;
		int cellX = 0;
		int cellY = 0;
		int left = 0;
		int top = 0;
		for (int i = 0; i < getChildCount(); i++) {
			child = (CellView) getChildAt(i);
			info = child.appInfo;
			cellX = info.cellX;
			cellY = info.cellY;
			left = (int) getMChildLeft(cellX);
			top = (int) getMChildTop(cellY);
			child.layout(left, top, (int) (left + mCellWidth),
					(int) (top + mCellHeigth));
		}

	}

	public float getMChildTop(int cellY) {
		return cellY * cellHeight + getPaddingTop()
				+ (cellHeight - mCellHeigth) / 2;
	}

	public float getMChildLeft(int cellX) {
		return cellX * cellWidth + getPaddingLeft() + (cellWidth - mCellWidth)
				/ 2;
	}

	/**
	 * 是否还有空位
	 * 
	 * @return
	 */
	public boolean isEmpty() {
		return getChildCount() == 0 ? true : false;
	}

	/**
	 * 根据当前的X , Y 值找出当前的地方应用图标
	 * 
	 * @param x
	 * @param y
	 * @return
	 */
	public View isExists(int x, int y, int width, int height) {
		final int centerX = x + width / 2;
		final int centerY = y + height / 2;
		View view = null;
		for(int i = 0 ; i < getChildCount() ; i++ ){
			view = getChildAt(i);
			if ((view.getLeft() < centerX && view.getTop() < centerY)
					&& (view.getRight() > centerX && view.getBottom() > centerY)) {
				return view;
			}
		}
		return null;
	}
	
	/**
	 * 返回当前的应用的状态,-1 为此应用不存在,其实为View.VISIBLE;View.GONE
	 * @param appInfo
	 */
	public int getCellViewStatu(AppInfo appInfo){
		CellView cellView = null;
		for(int i = 0 ; i < getChildCount() ; i ++){
			cellView = (CellView) getChildAt(i);
			if(appInfo.eqXYScreen(cellView.appInfo)){
				return cellView.getVisibility();
			}
		}
		return -1;
	}

	/**
	 * 此页是否已满
	 * 
	 * @return
	 */
	public boolean isFull() {
		return getChildCount() == clos * rows ? true : false;
	}

	/**
	 * 找到最后一个应用的位置
	 * 
	 * @return
	 */
	public int[] findLastAppView() {
		int cell[] = null;
		if (isEmpty()) {
			cell = new int[] { 0, 0 };
		} else if (!isFull()) {
			int maxX = 0;
			int maxY = 0;
			AppInfo info = null;
			for (int i = 0; i < getChildCount(); i++) {
				info = ((CellView) getChildAt(i)).appInfo;
				final int infoCellX = info.cellX;
				final int infoCellY = info.cellY;
				Log.i(TAG, "findLastAppview AppInfo=" + info);
				if (maxY < infoCellY) {
					maxY = infoCellY;
					maxX = infoCellX;
				} else if (maxY == infoCellY && maxX < infoCellX) {
					maxX = infoCellX;
				}
			}
			Log.d(TAG, "find screenId  max cellXY maxX=" + maxX + " maxY="
					+ maxY);
			// 找到最大的一格了
			cell = new int[] { maxX, maxY };
		}
		return cell;
	}

	/**
	 * 找到最后一个空位
	 * 
	 * @return
	 */
	public int[] findLastEmptyAppView() {
		int cell[] = null;
		if (isEmpty()) {
			cell = new int[] { 0, 0 };
		} else {
			cell = findLastAppView();
			cell = findViewNext(cell[0], cell[1]);
		}
		return cell;
	}

	/**
	 * 删除一个应用
	 * 
	 * @param appInfo
	 * @return
	 */
	public boolean removeAppView(final AppInfo appInfo, Animation scale,
			int visible) {
		final int index = findApp(appInfo, visible);
		Log.d(TAG, "removeAppView index=" + index + "appinfo=" + appInfo);
		if (-1 != index) {
			final View delVew = getChildAt(index);
			if (null != scale) {
				scale.setAnimationListener(new ViewAnimationListener() {

					@Override
					public void onAnimationEnd(Animation animation) {
						super.onAnimationEnd(animation);
						handler.sendMessage(handler.obtainMessage(DEL_VIEW,
								index, 0));
						handler.sendMessage(handler.obtainMessage(DEL_MOVE,
								appInfo.cellX, appInfo.cellY, true));
					}

				});
				delVew.startAnimation(scale);
			} else {
				handler.sendMessage(handler.obtainMessage(DEL_VIEW, index, 0));
				handler.sendMessage(handler.obtainMessage(DEL_MOVE,
						appInfo.cellX, appInfo.cellY, false));
			}

		}
		return true;
	}

	/**
	 * 添加一个应用
	 * 
	 * @param appInfo
	 * @return
	 * 
	 *         public boolean addAppView(AppInfo appInfo){ CellView child =
	 *         (CellView)
	 *         Utils.getLayoutInflater(mContext).inflate(R.layout.cell, null);
	 *         child.appInfo = appInfo; child. addView(child ); return true; }
	 */
	/**
	 * 当删除一个应用了,整理其它的
	 * 
	 * @param delXY
	 */
	public void clearUp(final int cellX, final int cellY, final boolean isAnim) {
		final List<CellView> moves = new ArrayList<CellView>();
		CellView cellView = null;
		int next[] = findViewNext(cellX, cellY);
		if (null != next) {
			int viewId = 0;
			while (-1 != (viewId = findApp(next[0], next[1], View.VISIBLE))) {
				cellView = (CellView) getChildAt(viewId);
				next = findViewNext(cellView.appInfo.cellX,
						cellView.appInfo.cellY);
				moves.add(cellView);
			}
			for (CellView view : moves) {
				moveToPre(view, isAnim);
			}
		}

	}

	/**
	 * 根据AppInfo找到view的索引
	 * 
	 * @param appInfo
	 * @param visible
	 * @return
	 */
	public int findApp(AppInfo appInfo, int visible) {
		return findApp(appInfo.cellX, appInfo.cellY, visible);
	}

	/**
	 * 根据appinfo找以view的索引
	 * 
	 * @param appInfo
	 * @return
	 */
	private int findApp(int cellX, int cellY, int visible) {
		CellView temp = null;
		for (int i = 0; i < getChildCount(); i++) {
			temp = (CellView) getChildAt(i);
			if (temp.appInfo.cellX == cellX && temp.appInfo.cellY == cellY
					&& temp.getVisibility() == visible) {
				return i;
			}
		}
		return -1;
	}

	public View findAppView(AppInfo appInfo, int visible) {
		return findAppView(appInfo.cellX, appInfo.cellY, visible);
	}

	/**
	 * 默认查找可视的应用
	 * 
	 * @param appInfo
	 * @return
	 */
	public View findAppView(AppInfo appInfo) {
		return findAppView(appInfo.cellX, appInfo.cellY, VISIBLE);
	}

	/**
	 * 根据appinfo找出Cellview
	 * 
	 * @param appInfo
	 * @return
	 */
	private View findAppView(int cellX, int cellY, int visible) {
		final int viewIndex = findApp(cellX, cellY, visible);
		return viewIndex != -1 ? getChildAt(viewIndex) : null;
	}

	/**
	 * 两个应用交换位置
	 * 
	 * @param appInfo1
	 * @param appInfo2
	 * @return
	 */
	public boolean swapAppView(AppInfo appInfo1, AppInfo appInfo2) {
		
		return true;
	}

	/**
	 * 返回上一个应用的cellx ,cellY
	 * 
	 * @param cellX
	 * @param cellY
	 * @return
	 */
	public int[] findViewPro(int cellX, int cellY) {
		int fCellX = 0;
		int fCellY = 0;
		if (cellX == 0 && cellY == 0) {
			return null;
		} else {
			if (cellX == 0) {
				fCellX = (int) (clos - 1);
				fCellY = cellY - 1;
			} else {
				fCellX = cellX - 1;
				fCellY = cellY;
			}
		}
		return new int[] { fCellX, fCellY };
	}

	/**
	 * 查找下一个
	 * 
	 * @param cellX
	 * @param cellY
	 * @return
	 */
	public int[] findViewNext(int cellX, int cellY) {
		int fCellX = 0;
		int fCellY = 0;
		if (cellX == clos && cellY == rows) {
			return null;
		} else if (cellX != clos - 1) {
			fCellX = cellX + 1;
			fCellY = cellY;
		} else {
			fCellY = cellY + 1;
		}
		return new int[] { fCellX, fCellY };
	}

	/**
	 * 移动到哪个
	 * 
	 * @param cellView
	 * @param cellX
	 * @param cell
	 */
	public void moveToXY(final CellView cellView, final int cellX,
			final int cellY, boolean isAnim) {
		if (!isAnim) {
			resetCellView(cellView, cellX, cellY);
		} else {
			Animation animation = new TranslateAnimation(0.0f,
					getMChildLeft(cellX) - cellView.getLeft(), 0.0f,
					getMChildTop(cellY) - cellView.getTop());
			animation.setDuration(MOVE_ICON_TIME);
			animation.setAnimationListener(new ViewAnimationListener() {

				@Override
				public void onAnimationEnd(Animation animation) {
					super.onAnimationEnd(animation);
					resetCellView(cellView, cellX, cellY);
				}

			});
			animation.setFillEnabled(true);
			cellView.startAnimation(animation);
		}

	}

	/**
	 * 把应用向下一个移动
	 * 
	 * @param cellView
	 */
	public void moveToNext(CellView cellView, boolean isAnim) {
		if (null != cellView && null != cellView.appInfo) {
			AppInfo appInfo = cellView.appInfo;
			int[] nextPoint = findViewNext(appInfo.cellX, appInfo.cellY);
			if (null != nextPoint) {
				moveToXY(cellView, nextPoint[0], nextPoint[1], isAnim);
			}
		}
	}

	/**
	 * 固定应用的位置
	 * 
	 * @param cellView
	 * @param cellX
	 * @param cellY
	 */
	private void resetCellView(final CellView cellView, final int cellX,
			final int cellY) {
		cellView.appInfo.cellX = cellX;
		cellView.appInfo.cellY = cellY;
		int left = (int) getMChildLeft(cellX);
		int top = (int) getMChildTop(cellY);
		cellView.layout(left, top, left + cellWidth, top + cellHeight);
	}

	/**
	 * 把应用向上一个移动
	 * 
	 * @param cellView
	 */
	public void moveToPre(CellView cellView, boolean isAnim) {
		if (null != cellView && null != cellView.appInfo) {
			AppInfo appInfo = cellView.appInfo;
			int[] prePoint = findViewPro(appInfo.cellX, appInfo.cellY);
			if (null != prePoint) {
				moveToXY(cellView, prePoint[0], prePoint[1], isAnim);
			}
		}
	}

}
